#include "GWidget.h"

void
g_widget_init(GWidget *           self,
              GWidgetNumsCallback width_cb,
              GWidgetNumsCallback height_cb,
              GWidgetRender       render)
{
        self->get_min_width  = width_cb;
        self->get_min_height = height_cb;
        self->render         = render;
        self->is_update      = false;
        self->next           = NULL;
        self->margin         = 0;
        self->align          = G_ALIGN_CENTER;
        self->is_rendering   = false;
        self->force_render   = false;
}

void
g_widget_set_align(GWidget *self, const GAlign align)
{
        self->align = align;
}

void
g_widget_set_margin(GWidget *self, const uint8_t margin)
{
        self->margin = margin;
}

uint16_t
g_widget_get_min_width(GWidget *self)
{
        const uint16_t width = self->get_min_width(self) + 2 * self->margin;
        return width > SCREEN_WIDTH ? SCREEN_WIDTH : width;
}

uint16_t
g_widget_get_min_height(GWidget *self)
{
        const uint16_t height = self->get_min_height(self) + 2 * self->margin;
        return height > SCREEN_HEIGHT ? SCREEN_HEIGHT : height;
}

void
g_widget_render(GWidget *      self,
                const uint16_t startX,
                const uint16_t startY,
                const uint16_t endX,
                const uint16_t endY)
{
        /* 防止因带渲染功能的中断打断当前渲染，同一对象重复渲染将导致未知错误 */
        if (self->is_rendering)
                return;
        self->is_rendering = true;

        if (self->render)
                self->render(self, startX, startY, endX, endY);

        self->is_rendering = false;
        self->force_render = false;
}

void
g_widget_set_force_render(GWidget *self)
{
        self->force_render = true;
}
